package com.common.hbase.liaison;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ParseInterface<T>{

    private static final Logger log = LoggerFactory.getLogger(ParseInterface.class);

    /*
     *  解析scan
     * */
    public List<T> parseScan(Class<T> aClass , ResultScanner resultScanner){
        List<T> list = new ArrayList<>();
        try {
            for (Result result : resultScanner) {
                List<Cell> cells = result.listCells();
                T o = parseGet(aClass, (Cell[]) cells.toArray());
                list.add(o);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }


    public T parseGet(Class<T> aClass,Cell[] cells){
        try {

            Field[] declaredFields = aClass.getDeclaredFields();
            T o = aClass.newInstance();
            for (Cell cell : cells) {
                String filedName = Bytes.toString(CellUtil.cloneQualifier(cell));
                boolean flag = false;
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    if(filedName.equals(declaredField.getName())) {
                        flag = true;
                        Class fieldType = declaredField.getType();
                        Constructor constructor = fieldType.getConstructor(String.class);
                        Object o2 = constructor.newInstance(Bytes.toString(CellUtil.cloneValue(cell)));
                        declaredField.set(o, o2);

                    }
                }
                if (!flag){
                    throw new NullPointerException(filedName+"找不到");
                }
            }
            return o;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
